package com.juc.concurrency.jucExample.threadLocal.example;

/**
 * @author huangweiyue
 * @description InheritableThreadLocal子线程可以访问到父线程的值
 * InheritableThreadLocal源码注释翻译：
 * 可继承的线程局部变量使用优先于普通线程局部变量（即ThreadLocal）
 * 是当之前线程的属性被保存在变量(例如,用户ID、事务ID)必须被自动传送到任何子线程创建的情况下
 * @date Created in 2021-07-27
 */
public class InheritableThreadLocalExample {
    /**
     * 输出结果，work thread:null。这是合理的 表明ThreadLocal是每个线程的副本
     */
//    public static ThreadLocal<String> threadLocal = new ThreadLocal<>();

    /**
     * InheritableThreadLocal子线程可以访问到父线程的值
     */
    public static ThreadLocal<String> threadLocal = new InheritableThreadLocal<>();

    public static void main(String[] args) {
        threadLocal.set("hello world");
        Thread thread = new Thread(() -> System.out.println("work thread:" + threadLocal.get()));
        thread.start();
        System.out.println("main thread:" + threadLocal.get());
    }
}
